<template>
  <div class="subject-page">
    <!-- 页面头部 -->
    <div class="header">
      <h2>学科管理</h2>
      <el-button type="primary" @click="showAddDialog">添加学科</el-button>
    </div>

    <!-- 学科列表 -->
    <div class="subject-list-grid">
      <div class="subject-card" v-for="subject in subjectList" :key="subject.id">
        <div class="card-header">
          <span class="subject-title">{{ subject.subject }}</span>
          <div class="subject-actions">
            <el-button type="primary" link @click="handleEdit(subject)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button type="danger" link @click="handleDelete(subject)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="card-content">
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>创建时间：{{ formatDate(subject.createTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><List /></el-icon>
            <span>任务数量：{{ subject.studyMissionList?.length || 0 }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>总时长：{{ formatTotalTime(subject.studyMissionList) }}</span>
          </div>
        </div>
      </div>
      <el-empty v-if="subjectList.length === 0" description="暂无学科" />
    </div>

    <!-- 添加/编辑学科对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingSubject ? '修改学科' : '添加学科'"
      width="500px"
    >
      <el-form
        ref="subjectFormRef"
        :model="subjectForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学科名称" prop="subject">
          <el-input v-model="subjectForm.subject" placeholder="请输入学科名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Calendar, List, Timer } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据列表
const subjectList = ref([])

// 计算顶部统计卡片数据
const subjectStatistics = computed(() => {
  const stats = []
  const subjects = {
    '数学': { time: '0小时', class: 'math', icon: 'List' },
    '英语': { time: '0小时', class: 'english', icon: 'List' },
    '政治': { time: '0小时', class: 'politics', icon: 'List' },
    '专业课': { time: '0小时', class: 'professional', icon: 'List' }
  }

  subjectList.value.forEach(subject => {
    let totalSeconds = 0
    if (subject.studyMissionList && subject.studyMissionList.length > 0) {
      subject.studyMissionList.forEach(mission => {
        if (mission.totalTime) {
          const [hours, minutes, seconds] = mission.totalTime.split(':').map(Number)
          totalSeconds += hours * 3600 + minutes * 60 + seconds
        }
      })
    }

    const hours = Math.floor(totalSeconds / 3600)
    let displayName = subject.subject
    let className = 'default'

    // 映射学科名称和样式
    switch (subject.subject) {
      case '高等数学':
        displayName = '数学'
        className = 'math'
        break
      case '英语':
        className = 'english'
        break
      case '政治':
        className = 'politics'
        break
      case '408':
        displayName = '专业课'
        className = 'professional'
        break
    }

    stats.push({
      name: displayName,
      time: hours > 0 ? `${hours}小时` : '暂无记录',
      class: className,
      icon: 'List'
    })
  })

  return stats
})

// 对话框控制
const dialogVisible = ref(false)
const editingSubject = ref(null)
// 用 reactive 定义表单对象
const subjectForm = reactive({
  subject: ''
})

// 表单验证规则
const rules = {
  subject: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化总时长
const formatTotalTime = (missionList) => {
  if (!missionList || missionList.length === 0) return '暂无学习记录'
  
  let totalSeconds = 0
  missionList.forEach(mission => {
    if (mission.totalTime) {
      const [hours, minutes, seconds] = mission.totalTime.split(':').map(Number)
      totalSeconds += hours * 3600 + minutes * 60 + seconds
    }
  })
  
  if (totalSeconds === 0) return '暂无学习记录'
  
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60
  
  let result = ''
  if (hours > 0) result += `${hours}小时`
  if (minutes > 0) result += `${minutes}分`
  if (seconds > 0) result += `${seconds}秒`
  
  return result || '暂无学习记录'
}

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const response = await axios.get('/api/subject/list')
    if (response.data.code === '200') {
      let arr = response.data.data?.data
      if (!Array.isArray(arr)) arr = []
      subjectList.value = arr
    } else {
      ElMessage.error(response.data.message || '获取学科列表失败')
    }
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogVisible.value = true
  editingSubject.value = null
  subjectForm.subject = ''
}

// 处理编辑
const handleEdit = (subject) => {
  editingSubject.value = subject
  subjectForm.subject = subject.subject
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (subject) => {
  try {
    await ElMessageBox.confirm('确定要删除这个学科吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/api/subject/${subject.id}/delete`)
    if (response.data.code === '200') {
      ElMessage.success('删除成功')
      fetchSubjectList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    const data = {
      subject: subjectForm.subject
    }
    
    if (editingSubject.value) {
      data.id = editingSubject.value.id
    }
    
    const response = await axios.post('/api/subject/add', data)
    
    if (response.data.code === '200') {
      ElMessage.success(editingSubject.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchSubjectList()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 组件挂载时获取列表
onMounted(() => {
  fetchSubjectList()
})
</script>

<style scoped>
.subject-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.header .el-button {
  background: white;
  border: none;
  color: #409EFF;
  font-weight: 500;
  padding: 12px 24px;
  height: auto;
  transition: all 0.3s ease;
}

.header .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.2);
}

.subject-list-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
  margin-top: 20px;
}

.subject-card {
  height: 100%;
  transition: all 0.3s ease;
  border: none;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.subject-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.card-header::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 100%);
  pointer-events: none;
}

.subject-title {
  font-size: 18px;
  font-weight: 500;
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.subject-actions {
  display: flex;
  gap: 8px;
  z-index: 1;
}

.subject-actions .el-button {
  color: white;
  border: none;
  padding: 8px;
  height: 32px;
  width: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
}

.subject-actions .el-button:hover {
  transform: translateY(-2px);
  background: rgba(255, 255, 255, 0.3);
}

.subject-actions .el-button.is-link {
  color: white;
}

.card-content {
  padding: 24px;
  background: white;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .el-icon {
  font-size: 18px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.el-empty {
  padding: 60px;
  background: white;
  border-radius: 16px;
  margin-top: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.el-dialog {
  border-radius: 20px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  padding: 20px;
  margin-right: 0;
}

.el-dialog__title {
  color: white;
  font-size: 18px;
  font-weight: 500;
}

.el-dialog__headerbtn {
  top: 20px;
  right: 20px;
}

.el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.el-dialog__body {
  padding: 30px;
}

.el-dialog__footer {
  padding: 20px 30px;
  border-top: 1px solid #edf2f7;
  background: #f8fafc;
}

.dialog-footer .el-button {
  padding: 12px 24px;
  font-weight: 500;
  min-width: 100px;
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  border: none;
  transition: all 0.3s ease;
}

.dialog-footer .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

/* 添加顶部统计卡片样式 */
.statistics-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.card-icon {
  font-size: 24px;
  padding: 12px;
  border-radius: 8px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-time {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-name {
  font-size: 14px;
  color: #666;
}

/* 不同学科的颜色样式 */
.math .card-icon {
  background: #409EFF;
}

.english .card-icon {
  background: #67C23A;
}

.politics .card-icon {
  background: #E6A23C;
}

.professional .card-icon {
  background: #F56C6C;
}

.default .card-icon {
  background: #909399;
}
</style> 